package logic

import (
	"context"

	"googee/service/addrbook/rpc/addrbook"
	"googee/service/addrbook/rpc/internal/svc"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type SetDefaultAddrBookLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSetDefaultAddrBookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetDefaultAddrBookLogic {
	return &SetDefaultAddrBookLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 设置默认地址
func (l *SetDefaultAddrBookLogic) SetDefaultAddrBook(in *addrbook.AddrIdRequest) (*addrbook.AddrBookInfo, error) {
	resp := &addrbook.AddrBookInfo{}
	// book, err := l.svcCtx.AddrbookModel.FindOneByIdUserId(l.ctx, in.Id, in.UserId)

	err := l.svcCtx.SqlConn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		book, err := l.svcCtx.AddrbookModel.FindOneByIdUserId(l.ctx, in.Id, in.UserId)
		if err != nil || book == nil {
			return err
		}
		book.IsDefault = 1
		l.svcCtx.AddrbookModel.Update(ctx, book)

		books, _ := l.svcCtx.AddrbookModel.FindAllByUserId(l.ctx, in.UserId)
		for _, book := range books {
			if book.Id != in.Id {
				book.IsDefault = 0
				l.svcCtx.AddrbookModel.Update(ctx, book)
			}
		}
		return nil
	})

	if err != nil {
		return nil, status.Error(codes.NotFound, "not found addressbook")
	}
	book, err := l.svcCtx.AddrbookModel.FindOneByIdUserId(l.ctx, in.Id, in.UserId)
	if err != nil || book == nil {
		return nil, status.Error(codes.NotFound, "not found addressbook")
	}

	copier.Copy(&resp, book)
	return resp, nil
}
